package com.Lyoto.NetNotify.Utils;

import com.Lyoto.NetNotify.Constraint.ExceptionEnum;
import com.Lyoto.NetNotify.Exceptions.ConfigErrorException;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author Lyoto
 * @Description
 * @Date 2022-09-19 15:38
 * @Version
 **/
public class FileUtils {
    /**
     * 读取tag
     *
     * @param tag 标志
     *
     * @return value
     */
    public static String readFileToTag(String tag) {
        StringBuilder stb = new StringBuilder();
        BufferedReader fileReader = null;
        try {
            InputStream inputStream = FileUtils.class.getClassLoader().getResourceAsStream("config.yml");
            if (inputStream == null){
                throw new ConfigErrorException(ExceptionEnum.CONFIG_ERROR);
            }
    
            fileReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
           
            char[] chars = new char[1024];
            int offset;
            while ((offset = fileReader.read(chars))!= -1) {
                stb.append(chars,0,offset);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        String s = stb.toString();
        if (s.isEmpty()){
            throw new ConfigErrorException(ExceptionEnum.CONFIG_ERROR);
        }
        if (!s.contains(tag)){
            throw new ConfigErrorException(ExceptionEnum.TAG_ERROR);
        }
        int i = s.indexOf(tag + ':')+tag.length() + 1;
        int i1 = i + s.substring(i).indexOf(10) - 1;
        return s.substring(i, i1 < i ? s.length(): i1).trim();
    }
    
    public static void main(String[] args) {
        String s = readFileToTag("mail.email-name");
        System.out.println(s);
    }
}
